﻿using LxBasic;
using LxLESS;
using System.Collections.Generic;

namespace LxCore
{
    public class ResidualMonitor : MonitorBase, IIsEmpty
    {
        public ResidualMonitor(string name, Func<ZoneCFDFields, ICalResidual?> getCalRes)
        {
            this.Name = name;
            this.GetCalRes = getCalRes;
            this.DefaultValue = 1;
        }
        public void CheckCreate()
        {
            Residuals.Clear();
            foreach (var zf in LxSim.Sim.Fields.ZoneFields)
            {
                var cal = GetCalRes(zf);
                if (cal != null)
                {
                    Residuals.Add(cal);
                }
            }
        }
        protected Func<ZoneCFDFields, ICalResidual?> GetCalRes;
        protected List<ICalResidual> Residuals = new List<ICalResidual>();
        public bool IsEmpty => Residuals == null || Residuals.Count == 0;
        public override void ClearHistory()
        {
            base.ClearHistory();
            Residuals.Clear();
        }
        public override void RunStatistic()
        {
            LatestValue = 0;
            if (IsLatestValueValid = Residuals.Count > 0)
            {
                foreach (var s in Residuals)
                {
                    (bool v, double res) = s.GetResidualReset();
                    if (res > LatestValue)
                    {
                        LatestValue = res;
                    }
                }
            }
        }
    }
}